package com.example.multilevelapprovalback.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
    private static final String OPTIONS = "OPTIONS";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        log.info("crosFilter");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有来源的跨域访问
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); // 允许的请求方法
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "*"); // 允许所有请求头的跨域访问
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true"); // 允许发送身份验证信息（如Cookies、HTTP认证或客户端SSL证书）
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600"); // 预检请求的有效期，单位为秒

        // 如果是OPTIONS则结束请求
        if (OPTIONS.equals(((HttpServletRequest) servletRequest).getMethod())) {
            httpServletResponse.getWriter().println("ok");
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
